﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Slam.Logging;

namespace Slam
{
	public class SlamType
	{	
		public SlamActionCollection Actions
		{
			get
			{
				return SlamContext.GetTypeActionCollection(Id);
			}
		}

		private string _id;
		public string Id
		{
			get
			{
				return _id;
			}
		}

		private string _name;
		public string Name
		{
			get
			{
				return _name;
			}
		}

		public SlamType(string id)
		{
			_id = id;
			SlamContext.RegisterTypeActionCollection(Id, new SlamActionCollection());
		}

		public SlamType(SPList list)
		{
			_id = list.ID.ToString();
			SlamContext.RegisterTypeActionCollection(Id, new SlamActionCollection());
		}

		public SlamType(SPContentType contentType)
		{
			_id = contentType.Id.ToString();
			SlamContext.RegisterTypeActionCollection(Id, new SlamActionCollection());
		}

		public void ExecuteActions(SlamEvent slamEvent, SPListItem listItem)
		{
			ILogger logger = ComponentService.GetInstance<ILogger>();
			
			foreach (var action in Actions.GetEventActions(slamEvent))
			{
				logger.LogMessage("Information", "Executing action: Type: " + action.Event + ", Id: " + action.Id);
				try
				{
					action.Execute(listItem);
				}
				catch (Exception ex)
				{
					logger.LogMessage("Exception", ex.ToString());
				}
				logger.LogMessage("Information", "Finished Executing action: Type: " + action.Event + ", Id: " + action.Id);
			}
		}
	}
}
